/**
 * 
 */
package com.zc.springproject.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSON;
import com.zc.springproject.serviceimpl.UserServiceImpl;

/**
 * @author ZhangCheng
 * @time 2019年10月31日
 */

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	
	private UserServiceImpl uSI;
	private ApplicationContext ioc;
	/**
	 * 
	 */
	private static final long serialVersionUID = 5198929293126014675L;

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		System.out.println("init");
		String xmlPath = "applicationSpringContext.xml";
		this.ioc = new ClassPathXmlApplicationContext(xmlPath);

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String userName = req.getParameter("userName");
		String pwd = req.getParameter("pwd");
		this.uSI = (UserServiceImpl) this.ioc.getBean("userServiceImpl");
		boolean Right = this.uSI.isRigthPwd(userName, pwd);
		System.out.println(Right);
		if (Right) {
			System.out.println("123");
//			sendMsgToHTMLWithFastJson(resp, "Yes");
//			req.getRequestDispatcher("success.jsp").forward(req, resp);
			resp.sendRedirect("success.html");
		} else {
			resp.sendRedirect("fail.html");
//			sendMsgToHTMLWithFastJson(resp, "No");
		}
	}

	/**
	 * 将对象包装成json格式给前端发送相应
	 */
	private void sendMsgToHTMLWithFastJson(HttpServletResponse resp, Object obj) throws ServletException, IOException {

		String msg = JSON.toJSONString(obj);
		System.out.println(msg);
		resp.setContentType("json/application;charset=UTF-8");
		resp.getWriter().write(msg);
	}
}
